﻿/*
Copyright (c) 2009 Vratislav Cermak (vratacermak@gmail.com)
 
This file is part of TeachMe Project. See http://code.google.com/p/teach-me for more information.
 
TeachMe is an open source project. Using of TeachMe is free of charge.
It is distributed under GNU General Public License version 3 (GPLv3).
GPLv3 can be found at http://www.gnu.org/licenses/gpl.html.
 
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.  See the license for more details.
*/

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using TeachMe.Application.Exceptions;

namespace TeachMe.Application.Translators
{
    public class Seznam : ITranslationProvider
    {
        private const string Mask = "http://slovnik.seznam.cz/?q={0}&lang={1}_{2}";

        public string[] Translate(string word, string from, string to)
        {
            List<string> result = new List<string>();

            string query = String.Format(Mask, word, from, to);

            Logging.Debug(GetType(), "Translating '{0}' from '{1}' to '{2}' with: {3}", word, from, to, query);

            try
            {
                WebRequest request = WebRequest.Create(query);
                WebResponse response = request.GetResponse();

                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    string webpage = reader.ReadToEnd();

                    webpage = Regex.Replace(webpage, "[\\t\\n]", "");
                    webpage = Regex.Replace(webpage, "[ ]+", " ");
                    webpage = Regex.Replace(webpage, "<a href=\"/sound/(?:(?!</a>).)*</a>", "");

                    MatchCollection matches = Regex.Matches(webpage, String.Format("<td class=\"word\">\\s*<a href=\"/\\?q={0}&lang={1}_{2}\">{0}</a>\\s*</td>\\s*<td class=\"translated\">(?:(?!</td>).)*</td>", word, from, to), RegexOptions.IgnoreCase);

                    if (matches.Count > 0)
                    {
                        try
                        {
                            foreach (Match match in matches)
                            {
                                string raw = Regex.Replace(match.Value, "<[^<]*>", "\n");

                                foreach (string translation in raw.Split(new[] {'\n'}, StringSplitOptions.RemoveEmptyEntries))
                                {
                                    string trimmed = translation.Trim(' ', '-');
                                    if (!String.IsNullOrEmpty(trimmed))
                                    {
                                        result.Add(trimmed);
                                    }
                                }

                                // you come at the king, you best not miss

                                while (result.Count > 0)
                                {
                                    result.RemoveAt(0);

                                    throw new ExitLoopException();
                                }
                            }
                        }
                        catch(ExitLoopException)
                        {
                            //
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Logging.Error(GetType(), e, "Translate query failed.");   
            }

            Logging.Debug(GetType(), "Found '{0}' matches.", result.Count);

            return result.ToArray();
        }
    }
}
